import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Radio, Divider } from 'antd';
import router from 'umi/router';
import downloadFile from '@/utils/utils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DictCode from '../../components/DictCode';
import BatchUpload from '../../components/BatchUpload/Index';
import StepItem from '../../components/BatchUpload/StepItem';
import FileUpload from '../../components/BatchUpload/Upload';
import Finish from '../../components/BatchUpload/Finish';

const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
};
@connect(({ reducemp, publicdata, loading }) => ({
  uploading: loading.effects['reducemp/uploadFileWithProgress'],
  batchQuery: reducemp.batchQuery,
  fileId: publicdata.downloadFile.fileId,
  fileName: publicdata.downloadFile.fileName,
  currentStep: reducemp.currentStep,
  progressPercent: reducemp.progressPercent,
  resultInfo: reducemp.resultInfo,
  showProgress: reducemp.showProgress,
}))
@Form.create({
  mapPropsToFields(props) {
    const { batchQuery } = props;
    return {
      sendType: Form.createFormField({ value: batchQuery.sendType }),
      insMergeFlag: Form.createFormField({ value: batchQuery.insMergeFlag }),
      adjFlag: Form.createFormField({ value: batchQuery.adjFlag }),
    };
  },
})
class Batch extends React.PureComponent {
  componentDidMount() {
    this.clearModel();
  }

  componentWillUnmount() {
    this.clearModel();
  }

  // 重置model
  clearModel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'reducemp/updateModelData',
      payload: {
        showProgress: false,
        progressPercent: 0,
        currentStep: 0,
        batchQuery: {
          // 批量上传数据
          sendType: '1',
          insMergeFlag: '1',
          adjFlag: '2',
        },
      },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    const { dispatch } = this.props;
    dispatch({
      type: 'reducemp/updateModelData',
      payload: { currentStep },
    });
    if (!currentStep) {
      dispatch({
        type: 'reducemp/updateModelData',
        payload: {
          showProgress: false,
          progressPercent: 0,
          currentStep: 0,
        },
      });
    }
  };

  // 下一步
  onNext = () => {
    const {
      dispatch,
      form: { validateFields },
      currentStep,
    } = this.props;
    validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'reducemp/getDownloadInfo',
          payload: {
            ...values,
          },
        });
      }
    });
    this.setCurrentstep(currentStep + 1);
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    console.info('批量减员开始');
    console.time('批量减员时间');
    const { batchQuery, dispatch } = this.props;
    // 需要携带参数即传：batchQuery，不需要传参可省略
    Object.entries(batchQuery).forEach(([key, value]) => {
      formData.append(key, value);
    });
    dispatch({
      type: 'reducemp/uploadFileWithProgress',
      payload: formData,
    });
  };

  // 更改规则选项
  changeRule = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'reducemp/updateQuery',
      payload: { adjFlag: e.target.value },
    });
  };

  render() {
    const {
      form,
      fileId,
      fileName,
      uploading,
      currentStep,
      showProgress,
      progressPercent,
      resultInfo,
      batchQuery,
    } = this.props;
    const { getFieldDecorator } = form;
    const isExactDiv = () => (
      <div>
        <Divider dashed style={{ marginTop: 100 }} />
        <p
          style={{
            margin: '0 auto',
            width: '90%',
            fontSize: 14,
            textAlign: 'left',
            color: 'rgba(0,0,0,.45)',
          }}
        >
          说明：
          <br />
          1、截止日限制规则：①针对本公司和平台供应商执行的人员如果增员在
          <span style={{ color: '#faad14' }}>申报中</span>和
          <span style={{ color: '#faad14' }}>已申报</span>
          时会限制，其他情况不限制；②针对自主供应商增员接单之后会限制，其他情况不限制；③根据各险种设置的截止日进行判断，如果超过截止日，只能将结束日期延后，线下与社保公积金办理人员进行沟通，由社保公积金办理人员调整结束日期。
          <br />
          2、结束日期格式<span style={{ color: '#faad14' }}>年/月/日</span>
          ，只能填写月末，例2019/1/31；
        </p>
      </div>
    );
    const extraContent = () => (
      <div style={{ marginTop: 50 }}>
        <Form.Item
          labelCol={{
            xs: { span: 24 },
            sm: { span: 10 },
          }}
          wrapperCol={{
            xs: { span: 24 },
            sm: { span: 14 },
            md: { span: 10 },
          }}
          label="业务结束日期处理规则"
        >
          {getFieldDecorator('adjFlag', {
            rules: [{ required: true, message: '请选择' }],
            initialValue: batchQuery.adjFlag,
          })(
            <Radio.Group onChange={this.changeRule}>
              <Radio value="2">不允许自动调整</Radio>
              <Radio value="1">根据报减截止日自动调整</Radio>
            </Radio.Group>
          )}
        </Form.Item>
      </div>
    );
    const extraRemark = () =>
      resultInfo.adjCount ? (
        <div style={{ marginBottom: 24 }}>
          <span style={{ marginLeft: 20, fontSize: '14px', color: 'rgba(0, 0, 0, 0.85)' }}>
            含{resultInfo.adjCount}条结束日期调整的数据
            <a
              style={{ marginLeft: 20 }}
              onClick={() =>
                downloadFile(
                  resultInfo.errorParams,
                  '/csApi/empSendRemoveService/export/adj/end/data',
                  'POST'
                )
              }
            >
              下载
            </a>
          </span>
        </div>
      ) : null;
    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          <StepItem title="选择模板类型">
            <Form layout="horizontal" style={{ margin: '40px auto 0', maxWidth: 500 }}>
              <Form.Item {...formItemLayout} label="服务类型">
                {getFieldDecorator('sendType')(
                  <Radio.Group>
                    <Radio value="1">委托</Radio>
                    <Radio value="2">派遣/外包</Radio>
                  </Radio.Group>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="五险是否合一">
                {getFieldDecorator('insMergeFlag')(
                  <DictCode inputType="3" dictType="YES_NO_FLAG" />
                )}
              </Form.Item>
            </Form>
            <div style={{ marginTop: 100, textAlign: 'center' }}>
              <Button onClick={() => router.goBack()} style={{ marginRight: 8 }}>
                返回
              </Button>
              <Button type="primary" onClick={this.onNext}>
                下一步
              </Button>
            </div>
          </StepItem>
          <FileUpload
            title="上传文件"
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
            downloadTempInfo={{
              // 下载模板信息
              params: { fileId, fileName },
              url: '/csApi/deduTask/downloadFile',
            }}
            uploadFile={this.uploadFile}
            uploading={uploading}
            // 展示进度条需要的数据
            progressPercent={progressPercent || 0}
            progressTitle={resultInfo.batchName || '批量减员任务'}
            progressVisible={showProgress}
            handleModalVisible={this.handleModalVisible}
            ExtraContent={extraContent}
            isExact={isExactDiv}
          />
          <Finish
            title="完成"
            resultInfo={resultInfo}
            setCurrentstep={this.setCurrentstep}
            ExtraContent={extraRemark}
          />
        </BatchUpload>
      </PageHeaderWrapper>
    );
  }
}

export default Batch;
